package cn.dogeye.service.impl;

import cn.dogeye.entity.SysAuth;
import cn.dogeye.entity.SysUser;
import cn.dogeye.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class MyUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(s))throw new RuntimeException("用户名不能为空");
        SysUser sysUser = sysUserService.getSysUserByName(s);
        if ( null==sysUser ) {
            throw new RuntimeException(String.format("用户名%s的帐号不存在",s));
        }
        List<String> auths = sysUser.getSysUserAuths().stream().map(SysAuth::getSysAuthName).collect(Collectors.toList());
        List<String> roles = sysUser.getSysUserRoles().stream().map(a->"ROLE_"+a.getSysRoleName()).collect(Collectors.toList());
        String authsString = Stream.of(auths, roles).flatMap(Collection::stream).distinct().collect(Collectors.joining(","));

        return new User(s,passwordEncoder.encode(sysUser.getSysUserPassword()),
                AuthorityUtils.commaSeparatedStringToAuthorityList(authsString)
                );
    }
}
